//
//  ServiceInfoDownload.m
//  Alfresco
//
//  Created by Michael Muller on 11/19/09.
//  Copyright 2009 Michael J Muller. All rights reserved.
//

#import "ServiceInfoDownload.h"
#import "Utility.h"

@implementation ServiceInfoDownload

@synthesize rootFolder;
@synthesize currentCollectionHref;
@synthesize elementBeingParsed;
@synthesize collectionAtomTitle;

- (void) dealloc {
	[rootFolder release];
	[currentCollectionHref release];
	[elementBeingParsed release];
	[collectionAtomTitle release];
	[super dealloc];
}

- (ServiceInfoDownload *) initWithDelegate: (id <AsynchronousDownloadDelegate>) del {
	NSString *h = userPrefHostname();
	NSString *p = userPrefPort();
	NSString *w = userPrefWebApp();
	NSString *protocol = userPrefProtocol();
	
	NSString *urlStr = [[NSString alloc] initWithFormat:@"%@://%@:%@%@/service/api/cmis", protocol, h, p, w];
	NSURL *u = [NSURL URLWithString:urlStr];
	[urlStr release];
	return (ServiceInfoDownload *) [self initWithURL:u delegate:del];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	
	// create a parser and parse the xml
	NSXMLParser *parser = [[NSXMLParser alloc] initWithData:self.data];
	[parser setDelegate:self];
	[parser parse];
	[parser release];
	
	[super connectionDidFinishLoading:connection];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {

	if ([elementName isEqualToString:@"collection"]) {
		self.currentCollectionHref = [attributeDict objectForKey:@"href"];
	}

	self.elementBeingParsed = elementName;
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
	self.elementBeingParsed = nil;
	if ([elementName isEqualToString:@"atom:title"]) {
		
		if ([self.collectionAtomTitle isEqualToString:@"root collection"]) {
			self.rootFolder = self.currentCollectionHref;
		}
		
		self.collectionAtomTitle = nil;
	}
}


- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
	if ([self.elementBeingParsed isEqualToString:@"atom:title"]) {
		self.collectionAtomTitle = self.collectionAtomTitle ? [self.collectionAtomTitle stringByAppendingString:string] : string;
	}
}


@end
